package com.example.springbootServiceNetwork.demos.web.Tool;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.example.springbootServiceNetwork.demos.web.Config.JwtInfo;
import com.example.springbootServiceNetwork.demos.web.Dto.SparkDto;
import com.example.springbootServiceNetwork.demos.web.Dto.SparkParamDto;
import okhttp3.HttpUrl;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 讯飞星火工具类
 */
public class SparkUtil {

    /**
     * 构建 鉴权方法
     * @param hostUrl
     * @param apiKey
     * @param apiSecret
     * @return
     * @throws Exception
     */
    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        // System.err.println(preStr);
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // System.err.println(sha);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();

        // System.err.println(httpUrl.toString());
        return httpUrl.toString();
    };

    /**
     * 构建请求参数
     * @param jwtInfo
     * @param appId
     * @param sparkParam
     * @return
     * @throws Exception
     */
    public static String getSparkJson(JwtInfo jwtInfo, String appId, SparkParamDto sparkParam) throws Exception {
        SparkDto sprarkDto = new SparkDto();
        //----------------payload-----------------
        JSONObject payload=new JSONObject();
          JSONObject message=new JSONObject();
            JSONArray text=new JSONArray();
              JSONObject textObj=new JSONObject();
              textObj.put("role","user");
              textObj.put("content",sparkParam.getContent());
            text.add(textObj);
          message.put("text",text);
        payload.put("message",message);
        sprarkDto.setPayload(payload);

        //----------------parameter-----------------

        JSONObject parameter=new JSONObject(); // parameter参数
        JSONObject chat=new JSONObject();
        chat.put("domain","generalv2");
        chat.put("temperature",0.5);
        chat.put("max_tokens",2000);
        parameter.put("chat",chat);
        sprarkDto.setParameter(parameter);

        //----------------header-----------------

        JSONObject header = new JSONObject();
        header.put("app_id", appId);
        header.put("uid", jwtInfo.getUserId());
        sprarkDto.setHeader(header);
        return JSON.toJSONString(sprarkDto);
    }

    /**
     * 构建请求参数Socket
     * @param appId
     * @param sparkParam
     * @return
     * @throws Exception
     */
    public static String getSparkJsonSocket(String appId, SparkParamDto sparkParam) throws Exception {
        SparkDto sprarkDto = new SparkDto();
        //----------------payload-----------------
        JSONObject payload=new JSONObject();
        JSONObject message=new JSONObject();
        JSONArray text=new JSONArray();
        JSONObject textObj=new JSONObject();
        textObj.put("role","user");
        textObj.put("content",sparkParam.getContent());
        text.add(textObj);
        message.put("text",text);
        payload.put("message",message);
        sprarkDto.setPayload(payload);

        //----------------parameter-----------------

        JSONObject parameter=new JSONObject(); // parameter参数
        JSONObject chat=new JSONObject();
        chat.put("domain","generalv2");
        chat.put("temperature",0.5);
        chat.put("max_tokens",2000);
        parameter.put("chat",chat);
        sprarkDto.setParameter(parameter);

        //----------------header-----------------

        JSONObject header = new JSONObject();
        header.put("app_id", appId);
        header.put("uid", sparkParam.getUserId());
        sprarkDto.setHeader(header);
        return JSON.toJSONString(sprarkDto);
    }





}
